﻿// Copyright (c) MichaConrad. All rights reserved. See License.txt in the project root for license information.

namespace LinqToLdapExtensions.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using System.Threading;
    using System.Web;
    using LinqToLdap;
    using Moq;

    [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Reviewed. Suppression is OK here.")]
    public class TestHelper
    {
        public static DirectoryContextFactory MockFactory(ScopeState state)
        {
            var config = new Mock<ILdapConfiguration>();
            config.Setup(p => p.ConnectionFactory).Returns(new Mock<LdapConnectionFactory>("server").Object);

            var factory = new DirectoryContextFactory(state, config.Object);
            return factory;
        }

        public static void MockHttpContext()
        {
            HttpContext.Current = new HttpContext(
                new HttpRequest(string.Empty, "http://tempuri.org", string.Empty),
                new HttpResponse(new StringWriter()));
        }

        public static Exception[] RunThreadedTest(int threads, int iterations, Action test)
        {
            var tasks = new List<Thread>();
            var errors = new List<Exception>();
            for (var i = 0; i < threads; i++)
            {
                var t = new Thread(() =>
                {
                    try
                    {
                        for (var m = 0; m < iterations; m++)
                        {
                            test();
                        }
                    }
                    catch (Exception ex)
                    {
                        errors.Add(ex);
                    }
                });
                t.Start();
                tasks.Add(t);
            }

            tasks.ForEach(t => t.Join());

            return errors.ToArray();
        }
    }
}
